package com.guagua.common.utils;

import com.guagua.common.exception.BusinessException;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

public class FileUtils {
    
    private static final String UPLOAD_DIR = "uploads";

    static {
        File dir = new File(UPLOAD_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }
    
    public static String saveFile(MultipartFile file, String uploadPath, String... allowedTypes) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (!Arrays.asList(allowedTypes).contains(contentType)) {
            throw new BusinessException("不支持的文件类型");
        }

        // 生成新的文件名
        String originalFilename = file.getOriginalFilename();
        String extension = StringUtils.getFilenameExtension(originalFilename);
        String newFilename = UUID.randomUUID().toString() + "." + extension;

        // 确保目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 保存文件
        try {
            File destFile = new File(uploadDir.getAbsolutePath() + File.separator + newFilename);
            file.transferTo(destFile);
            return newFilename;
        } catch (IOException e) {
            throw new BusinessException("文件上传失败");
        }
    }
} 